import React, {useState} from 'react';
import {Button, View} from '@tarojs/components';
import './index.scss';

interface StepperProps {
  value: number;
  min?: number;
  max?: number;
  step?: number;
  onChange?: (value: number) => void;
  onMin?: () => void;
  onMax?: () => void;
}

type actionType = '+' | '-';

const Stepper: React.FC<StepperProps> = ({
                                           value,
                                           min = 1,
                                           max = Infinity,
                                           step = 1,
                                           onChange,
                                           onMin,
                                           onMax,
                                         }) => {
  const [currentValue, setCurrentValue] = useState(value);

  const onSetCurrentValue = (actionType) => {
    setCurrentValue(prevValue => {
      const result = actionType === '+' ? prevValue + step : prevValue - step;
      onChange(result);
      return result;
    });
  }
  const handleDecrease = () => {
    if (currentValue - step >= min) {
      onSetCurrentValue('-')
    } else {
      console.log('执行了onMin')
      onMin && onMin();
    }
  };

  const handleIncrease = () => {
    if (currentValue + step <= max) {
      onSetCurrentValue('+')
    } else {
      onMax && onMax();
    }
  };

  return (
    <View className='align-center StepBox'>
      <Button size='mini' onClick={handleDecrease}>-</Button>
      <View className='value'>{currentValue}</View>
      <Button size='mini' onClick={handleIncrease}>+</Button>
    </View>
  );
};

export default Stepper;
